﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Data.Common;

namespace Runda.CMS.Dal
{
    public partial class WflTaskDal
    {
        public List<WflTaskEntity> GetMyTask(Guid UserID,List<SqlDbParameter> parameters, string OrderBy, int PageSize, int PageIndex, out int RecordCount)
        {
            List<WflTaskEntity> objList = new List<WflTaskEntity>();
            StringBuilder sqlStr = new StringBuilder()
                .AppendLine("select * from Cms_Wfl_Task ");
            sqlStr.Append(" where [Status] = 0 and TaskID in (select TaskID from  Cms_Wfl_TaskUser where UserID = @UserID) ");
            //sqlStr.AppendLine(" union  ");
            //sqlStr.AppendLine(" select * from Cms_Wfl_Task where TaskType=1 and activityid in (select activityid from Cms_Wfl_Comment where LeaderID=@userid)");
            sqlStr.AppendLine();
            string sql = SqlDbParameter.BuildSqlString(sqlStr.ToString(), parameters);

            string CmdText = @"WITH T AS
(
SELECT ROW_NUMBER() OVER(ORDER BY CreatedOn Desc) AS row_number, * 
  FROM ({0}) as A
)
SELECT * from T WHERE row_number > @StartRowNum AND  row_number <= @EndRowNum
select count(*) from ({1}) as B 
";

            CmdText = string.Format(CmdText, sql.ToString(), sql.ToString());

            DbCommand dbCommand = this._db.GetSqlStringCommand(CmdText);
            _db.AddInParameter(dbCommand, "@UserID", System.Data.DbType.Guid, UserID);
            _db.AddInParameter(dbCommand, "@StartRowNum", System.Data.DbType.Int32, (PageIndex - 1) * PageSize);
            _db.AddInParameter(dbCommand, "@EndRowNum", System.Data.DbType.Int32, PageIndex * PageSize);

            if(parameters != null)
            foreach (SqlDbParameter parameter in parameters)
            {
                parameter.SetDbCommond(dbCommand);
            }

            IDataReader reader = null;
            using (reader = _db.ExecuteReader(dbCommand))
            {
                objList = GetListFromReader<WflTaskEntity>(reader);
                if (reader.NextResult() && reader.Read())
                    RecordCount = reader.GetInt32(0);
                else
                    RecordCount = 0;
            }
            return objList; 
        }
    }
}
